/*
 * @Description:Socket 客户端 Client
 * 
 * @Author: rendc
 * 
 * @Date: 2025-08-25 11:06:31
 * 
 * @LastEditors: rendc
 * 
 * @LastEditTime: 2025-08-25 11:41:31
 */
// 客户端 Client

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TestSocket {
  public static void main(String[] args) throws Exception {
    // Client 连接服务器
    String ip = "127.0.0.1";
    int port = 8888;
    // 创建了一个客户端对象 用于连接指定的ip、port的服务器端
    Socket socket = new Socket(ip, port);
    System.out.println("客户端：成功连接：" + socket);
    // 获取IO流
    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    // 传输数据给服务器
    os.write("hello server,I'm client".getBytes());
    System.out.println("客户端：成功发送消息");
    // 接收服务端的消息
    byte[] buff = new byte[1024];
    int length = is.read(buff);
    System.out.println(new String(buff, 0, length));
    System.out.println("客户端：成功接收到服务端的消息");
    // 关闭资源
    os.close();
    is.close();
    // 关闭客户端连接对象
    socket.close();
  }

}